package com.choichumgming.rentcat.config;

import com.choichumgming.rentcat.web.controller.WebsocketServerEndpoint;
import io.micrometer.core.lang.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import javax.annotation.Resource;
import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {

    @Resource
    private WebsocketServerEndpoint webSocketServer;

    @Bean
    @Nullable
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler threadPoolScheduler = new ThreadPoolTaskScheduler();
        threadPoolScheduler.setThreadNamePrefix("SockJS-");
        threadPoolScheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        threadPoolScheduler.setRemoveOnCancelPolicy(true);
        return threadPoolScheduler;
    }

    //3.添加定时任务
    //@Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    @Scheduled(fixedRate=5*1000)
    private void configureTasks() throws Exception{
        CopyOnWriteArraySet<WebsocketServerEndpoint> websocketServerEndpoints = webSocketServer.websocketServerEndpoints;
        for (WebsocketServerEndpoint endpoint : websocketServerEndpoints) {
            try {
                endpoint.getSession().getBasicRemote().sendText("心跳检测");
                log.warn("心跳检测");
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}